package com.yaoqiang;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * @ClassName HelloZK
 * @Description TODO
 * @Author yaoqiang
 * @Date 2020/11/27 12:05
 * @Version 1.0
 */
public class HelloZK {
    private static final String CONNECTSTRING="192.168.55.214:2181";
    private static final String PATH="/sh";
    private static final int SESSION_TIMEOUT=50*1000;

    public static void main(String[] args) throws IOException, KeeperException,InterruptedException {
        HelloZK helloZK=new HelloZK();
        ZooKeeper zk=helloZK.startZK();
        Stat stat= zk.exists(PATH,false);
        if (stat==null){
            helloZK.createZNode(zk,PATH,"ZK1014");
            String result=helloZK.getZNode(zk,PATH);
            System.out.println("result:"+result);

        }else {
            System.out.println("znode has already ok");
        }
        helloZK.stopZK(zk);

    }

    private String getZNode(ZooKeeper zk, String path) throws KeeperException, InterruptedException {
        byte[] byteArray=zk.getData(path,false,new Stat());
        return new String(byteArray);
    }

    private void createZNode(ZooKeeper zk, String path, String nodeValue) throws KeeperException, InterruptedException {
        zk.create(path,nodeValue.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE,CreateMode.PERSISTENT);
    }

    private void stopZK(ZooKeeper zk)throws InterruptedException {
        if (zk!=null){
            zk.close();
        }
    }

    private ZooKeeper startZK() throws IOException {
        return new ZooKeeper(CONNECTSTRING, SESSION_TIMEOUT, new Watcher() {
            @Override
            public void process(WatchedEvent event) {

            }
        });
    }




}
